import moment from 'moment';
import request from '@/utils/request';

interface FormDataType {
  [propName: string]: any;
}
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

const isUrl = (path: string): boolean => reg.test(path);

const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

// 请求函数封装
const $http = (path: string, params: FormDataType, type: string = 'POST') =>
  request(path, { method: type, data: params });

/**
 * 检测数据类型，返回小写的字符串
 * @param data
 */
const types = (data: any): string =>
  Object.prototype.toString
    .call(data)
    .split('[object')[1]
    .replace(/\s|\]/g, '')
    .toLowerCase();

/**
 * 去掉前后空格
 * @param str 传递的字符串
 * @param is_global 去掉字符串中间的空格
 */
const trims = (str: string, is_global = '') => {
  let result;
  result = str.replace(/(^\s+)|(\s+$)/g, '');
  if (is_global.toLowerCase() === 'g') {
    result = result.replace(/\s/g, '');
  }
  return result;
};

// 日期格式化
const dateFormat = (date: any, format: string) => {
  const dateTime = new Date(date);
  const o = {
    'M+': dateTime.getMonth() + 1, // month
    'D+': dateTime.getDate(), // day
    'H+': dateTime.getHours(), // hour
    'm+': dateTime.getMinutes(), // minute
    's+': dateTime.getSeconds(), // second
    'q+': Math.floor((dateTime.getMonth() + 3) / 3), // quarter
    S: dateTime.getMilliseconds(), // millisecond
  };
  if (/(Y+)/.test(format)) {
    format = format.replace(RegExp.$1, `${dateTime.getFullYear()}`.substr(4 - RegExp.$1.length));
  }

  Object.keys(o).forEach(k => {
    if (new RegExp(`(${k})`).test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length),
      );
    }
  });
  return format;
};

/**
 * 初始化默认日期， antd日期默认为moment日期格式
 * @param date
 * @param endDateIsCurrent 结束时间是否置为当前时间
 */
const initDefaultDate = (date: number, endDateIsCurrent = false) => [
  moment()
    .subtract(date - 1, 'days')
    .startOf('day'),
  endDateIsCurrent ? moment() : moment().endOf('day'),
];

/**
 * 初始化默认日期， antd日期默认为moment日期格式
 * @param date
 * @param endDateIsCurrent 结束时间是否置为当前时间
 */
const initDefaultDateByMonths = (date: number, endDateIsCurrent = false) => [
  moment()
    .subtract(date - 1, 'months')
    .startOf('month'),
  endDateIsCurrent ? moment() : moment().endOf('day'),
];
/**
 * 传递参数转换日期
 * @param date 必须为moment日期格式或者时间戳
 * @param formatTime 是否格式化到秒
 */
const getFormatDate = (date: any, formatTime = false) => {
  const formatStr = formatTime ? 'YYYY-MM-DD HH:mm:ss' : 'YYYY-MM-DD';
  // 时间戳
  if (types(date) === 'number') {
    return moment(date).format(formatStr);
  }
  // moment日期
  return date.format(formatStr);
};

/**
 * 获取月的日期
 * @param data
 * @param format
 */
const getMonthDate = (data?: any, format = 'YYYY/MM') => {
  const dataParam = dateFormat(data || Date.now(), 'YYYY/MM/DD');
  return moment(dataParam, format);
};

/**
 * 获取月的日期
 * @param data
 * @param format
 */
const getYearDate = (data?: any, format = 'YYYY/MM/DD') => {
  const dataParam = dateFormat(data || Date.now(), 'YYYY/MM/DD');
  return moment(dataParam, format);
};

/**
 * 是否为json
 * @param str
 */
const isJson = (str: string) => {
  try {
    const obj = JSON.parse(str);
    return !!obj && typeof obj === 'object';
  } catch (e) {
    //
  }
  return false;
};

/**
 * 判断是否为空参数
 * @param param
 */
const isEmptyParam = (param: any) => param === '' || param === null || param === undefined;

/**
 * 字符串转对象方法
 * @param str
 */
const strToJson = (str: string) => {
  // eslint-disable-next-line no-new-func
  const json = new Function(`return ${str}`)();
  return json;
};

// 格式化时间
const toTime = (timestamp: string | number, format = 'YYYY-MM-DD H:mm:ss') => {
  if (!timestamp) {
    return '--';
  }
  return timestamp ? moment(timestamp).format(format) : timestamp;
};

export {
  isAntDesignProOrDev,
  isAntDesignPro,
  isUrl,
  $http,
  types,
  trims,
  initDefaultDate,
  initDefaultDateByMonths,
  getFormatDate,
  isJson,
  isEmptyParam,
  strToJson,
  toTime,
  dateFormat,
  getMonthDate,
  getYearDate,
};
